package cn.wolfcode.wolf2w.interceptor;

import cn.wolfcode.wolf2w.domain.UserInfo;
import cn.wolfcode.wolf2w.myannotation.RequiredLogin;
import cn.wolfcode.wolf2w.redis.service.IRedisService;
import cn.wolfcode.wolf2w.redis.test.RedisByKey;
import cn.wolfcode.wolf2w.util.JsonResult;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class LoginInceptor implements HandlerInterceptor {
    @Autowired
    private IRedisService redisService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        if(!(handler instanceof HandlerMethod)){
            return true;
        }
        //从请求头中去获取令牌
        String token = request.getHeader("token");
        System.out.println(token);
        String token1 = RedisByKey.USER_TOKEN.join(token);
        System.out.println(token1);
        //再从redis中去获取用户对象信息
        //UserInfo userInfo = (UserInfo) redisTemplate.opsForValue().get(token);
        String userInfo = redisService.getRedis(token1);
        System.out.println(userInfo);
        //判断当前的映射方法上面是否贴有自定义的注解
        HandlerMethod handlerMethod= (HandlerMethod) handler;
        if(handlerMethod.hasMethodAnnotation(RequiredLogin.class)){
            //若有的话，表示当前的映射方法需要登录验证
            //判断用户是否为空
            if(userInfo==null){
                response.setContentType("application/json;charset=utf-8");
                //将jsonResult中的nologin()的中的错误信息传到前端页面
                response.getWriter().write(JSON.toJSONString(JsonResult.noLogin()));
                return false;
            }
        }
        //若handlerMethod中不包含自定义注解的话，不用做登录验证，通行
        return true;
    }
}
